﻿using Project.API.Models.GoodModels;
using Project.BLL;
using Project.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Project.API.Controllers.GoodsControllers
{
    public class GoodsVisuController : ApiController
    {
        // GET api/<controller>
        /* 查询商品可视化数据*/
        public ResultData<GoodsVisualization> Get(DateTime? starttime=null, DateTime? endtime=null)
        {
            ResultData<GoodsVisualization> list = new ResultData<GoodsVisualization>();
            OrdersBll bll = new OrdersBll();
            GoodsVisualization data = new GoodsVisualization();
            var orders =new List<Orders>();

            //时间范围 筛选
            if (starttime != null && endtime != null)
            {
                starttime=starttime.Value.AddDays(1);
                endtime = endtime.Value.AddDays(1);

                orders = bll.Query().Where(x => x.CreateDate >= starttime && x.CreateDate <= endtime).ToList();
            }
            else {

                orders = bll.QueryList();
            }


            // 按天分组计算每天营业额
            var trendData = orders
                .GroupBy(o => o.CreateDate.Date) // 按日期分组
                .Select(g => new
                {
                    OrderDate = g.Key,          // 分组键（日期）
                    TotalRevenue = g.Sum(o => o.TotalAmount) // 计算总营业额
                })
                .OrderBy(r => r.OrderDate);    // 按日期排序

            data.trendData = (from a in trendData select new trends {
                    date=a.OrderDate,
                    sales=Convert.ToInt32(a.TotalRevenue)
            }).ToList();


            //按奶茶名称分组 计算每个奶茶的营业额

            var pies = orders
                .GroupBy(o => o.Goods.name) // 按日期分组
                .Select(g => new
                {
                    name= g.Key,          // 分组键（名称）
                    value = g.Sum(o => o.TotalAmount) // 计算总营业额
                })
                .OrderBy(r => r.name);    // 按日期排序

            data.pieData = (from a in pies
                              select new pies
                              {
                                  name = a.name,
                                  value = Convert.ToInt32(a.value)
                              }).ToList();


            list.data = data;
            return list;
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody] string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}